//
//  WmcPanZoomImageView.swift
//  YPWatermarkCamera
//
//  Created by yupao_ios_macmini06 on 2022/10/28.
//

import UIKit

class WmcPanZoomImageView: UIScrollView {
    
    @IBInspectable
    var imageName: String? {
        didSet {
            guard let imageName = imageName else {
                return
            }
            imageView.image = imageName.yp.uiImage
        }
    }
    
    var image: UIImage? {
        didSet {
            guard let image = image else {
                return
            }
            imageView.image = image
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    
    convenience init(imageName: String) {
        self.init(frame: .zero)
        self.imageName = imageName
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }
    
    private func commonInit() -> Void {
        // imageView
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.contentMode = .scaleAspectFit
        addSubview(imageView)
        
        let inset = (self.frame.height - Wmc_screenWidth) / 2
        
        imageView.snp.makeConstraints { make in
            make.top.equalTo(-inset)
            make.left.right.bottom.equalToSuperview()
            make.width.equalTo(Wmc_screenWidth)
            make.height.equalTo(Wmc_screenHeight - Wmc_safeAreaTop - 44)
        }
        
        // scrollView
        minimumZoomScale = 1
        maximumZoomScale = 3
        
        //self.updateMinZoomScaleForSize(self.bounds.size)
        
        showsHorizontalScrollIndicator = false
        showsVerticalScrollIndicator = false
        delegate = self
    
        // tap
        let doubleTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap(_:)))
        doubleTapRecognizer.numberOfTapsRequired = 2
        addGestureRecognizer(doubleTapRecognizer)
    }
    
    private lazy var imageView: UIImageView = {
        let view = UIImageView()
        view.contentMode = .scaleAspectFit
        return view
    }()
}

extension WmcPanZoomImageView: UIScrollViewDelegate {
    
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return imageView
    }
}

extension WmcPanZoomImageView {

    @objc private func handleDoubleTap(_ tap: UITapGestureRecognizer) -> Void {
        if zoomScale == 1 {
            setZoomScale(2, animated: true)
        } else {
            setZoomScale(1, animated: true)
        }
    }
}
